
'use strict';

const createConfig = require('uni-config-center');
const uidConfig = createConfig({
	pluginId: 'uni-id'
});

const db = uniCloud.database();
const dbcmd = db.command;

const { 
	wxapi,
	utils: wxutils
} = require('use-api');

// 微信公众号
const { h5wx } = require('../weixin');
// unipush
const unipush = require('../unipush');

const utils = require('../utils');

module.exports = {
	// 处理 post 消息
	postRequest: async function(req) {
		let res = '';
		try {
			
			if (!uidConfig.config('message-notify.enabled')) {
				return res;
			}
			
			if (uidConfig.config('message-notify.key') !== req.headers['message-notify-key']) {
				console.log('message-notify-key 异常', req.headers['message-notify-key']);
				return res;
			}
			
			const action = req.path.split('/').filter(x => x)[0];
			
			/**
			 { 
				id,
				scene,
				uname,
				url,
				title,
				content,
				...bizData
			 }
			 */
			const data = JSON.parse(req.body || '{}');
			const scene = parseInt(data.scene);
			
			// 通知消息类型
			const message = await utils.get_message(scene);
			
			if (!(message && message._id)) {
				console.log(`message scene: ${scene} 不存在`);
				return res;
			}
			console.log('message', message);
			
			// 通知 uids
			let uids = [];
			if (data.uid) {
				uids.push(data.uid);
			} else {
				uids = await utils.get_message_uids(message);
			}
			console.log('message uids', uids);
			
			switch (action){
				case '101':
				case '102':
					// 订单相关通知
					
					break;
				case 'aftersale':
					// 售后相关通知
					
					break;
				case '301':
				case '302':
				case '303':
				case '304':
				case '305':
				case '306':
					// 提现相关通知
					
					break;
				case '401':
					// 反馈相关通知
					
					break;
				default:
					console.log('message action 未接入', action);
					return res;
			}
			
			// 记录消息通知
			const messageAddRes = await db.collection('usemall-message').add({
				title: message.title,
				content: data.content || data.title,
				to_uids: uids,
				read_uids: [],
				del_uids: [],
				type: message.type,
				scene: parseInt(scene),
				mid: data.id,
				url: data.url,
				create_time: Date.now(),
				create_uid: 'message-notify'
			});
			console.log('messageAddRes', messageAddRes);
			
			data.mid = data.id;
			data.id = messageAddRes.id;
			
			// 发送微信公众号通知
			if (wxapi.message_notify_enabled && Object.keys(h5wx).includes('send_tpl_' + action)) {
				const h5wxRes = await h5wx['send_tpl_' + action](data);
				console.log('h5wxRes', h5wxRes, 'send_tpl_' + action, data);
			}
			
			// 发送 unipush 通知
			if (Object.keys(unipush).includes('send_msg_' + action)) {
				const unipushRes = await unipush['send_msg_' + action](uids, data);
				console.log('unipushRes', unipushRes, 'send_msg_' + action, uids, data);
			}
			
		} catch(e) {
			console.log('notifyfunc err', e);
		}
		
		return res;
	}
}

